package com.itheima.controller.user;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.constant.RedisMessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.UserMemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Slf4j
@RequestMapping("member")
@RestController
@Api(tags = "用户端登录")
public class UserMemberController {
    @Autowired
    private UserMemberService userMemberService;
    @Autowired
    private RedisTemplate redisTemplate;


    @PostMapping("login")
    @ApiOperation(value = "用户登录")
    public Result login(@RequestBody Map map) {

        //从redis中获取验证码
        String validateCodeRedis = (String) redisTemplate.opsForValue().get(map.get("telephone") + RedisMessageConstant.SENDTYPE_LOGIN);//获取验证码
        //截取redis中存储的验证码 保留后四位
        if (validateCodeRedis != null) {
            validateCodeRedis = validateCodeRedis.substring(validateCodeRedis.length() - 4);
        }

        String validateCode = (String) map.get("validateCode");

        //验证码进行比对
        if(validateCodeRedis != null && validateCodeRedis.equals(validateCode) && validateCode != null) {
            //成功则调用service方法完成登录
            userMemberService.login(map);
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        } else {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

    }
}
